"""Best-effort, typed DCC outcome telemetry.

The hub owns identity and delivery so managed tools never read or serialize a
credential themselves. Calls happen only after a useful output is committed;
the credential stays in the Authorization header and failures stay invisible
to the DCC operation.

`source` (the idempotency namespace) and `event_path` (the authenticated route)
come from the host adapter — the server assigns the analytics source from the
route, so a host posting to another host's route would mislabel its events.
"""

from __future__ import annotations

import os
import sys
import threading
import time
import uuid
from urllib.parse import urlparse

from . import api, config

TIMEOUT_SECONDS = 1.2
_PRODUCTION_HOSTS = {"threejs-blocks.com", "www.threejs-blocks.com"}


def _truthy(value) -> bool:
    return str(value or "").strip().lower() not in {"", "0", "false", "no", "off"}


def telemetry_state(site: str, env=None, argv=None) -> dict:
    """Explain whether outcome delivery is enabled or isolated."""
    env = os.environ if env is None else env
    argv = sys.argv if argv is None else argv
    if env.get("DO_NOT_TRACK") == "1":
        return {"enabled": False, "code": "do_not_track", "reason": "DO_NOT_TRACK=1"}
    if env.get("TB_TELEMETRY") == "0":
        return {"enabled": False, "code": "opt_out", "reason": "TB_TELEMETRY=0"}
    if _truthy(env.get("CI")):
        return {"enabled": False, "code": "ci", "reason": "CI environment"}
    if (
        env.get("PYTEST_CURRENT_TEST") is not None
        or env.get("NODE_ENV") == "test"
        or any("pytest" in str(arg).lower() or "unittest" in str(arg).lower() for arg in argv)
    ):
        return {"enabled": False, "code": "test", "reason": "test environment"}

    try:
        parsed = urlparse(str(site).rstrip("/"))
        production = parsed.scheme == "https" and parsed.hostname in _PRODUCTION_HOSTS and not parsed.path.strip("/")
    except (TypeError, ValueError):
        production = False
    if not production and env.get("TB_TELEMETRY") != "1":
        return {"enabled": False, "code": "non_production", "reason": "non-production site"}
    return {"enabled": True, "code": "enabled", "reason": "enabled"}


def _required_text(value, field: str, limit: int) -> str:
    text = str(value or "").strip()
    if not text or len(text) > limit:
        raise ValueError(f"Outcome telemetry requires {field} ({limit} characters maximum).")
    return text


def create_tool_job_completed_event(
    *,
    source: str,
    installation_id: str,
    tool: str,
    command_family: str,
    tool_version: str,
    output_kind: str,
    event_id: str | None = None,
    operation_id: str | None = None,
    occurred_at: int | None = None,
) -> dict:
    """Build the closed public v2 body; output paths and scene names cannot enter."""
    installation = _required_text(installation_id, "an installation ID", 160)
    operation = _required_text(operation_id or str(uuid.uuid4()), "an operation ID", 160)
    namespace = _required_text(source, "a source", 32)
    return {
        "eventId": _required_text(event_id or str(uuid.uuid4()), "an event ID", 160),
        "schemaVersion": 2,
        "name": "tool_job_completed",
        "occurredAt": int(time.time() * 1000) if occurred_at is None else int(occurred_at),
        "installationId": installation,
        "idempotencyKey": f"{namespace}:{installation}:{operation}",
        "properties": {
            "operationId": operation,
            "tool": _required_text(tool, "tool", 120),
            "commandFamily": _required_text(command_family, "command family", 120),
            "toolVersion": _required_text(tool_version, "tool version", 64),
            "outputKind": _required_text(output_kind, "output kind", 120),
        },
    }


def report_tool_job_completed(
    *,
    site: str,
    token: str | None,
    source: str,
    event_path: str,
    tool: str,
    command_family: str,
    tool_version: str,
    output_kind: str,
    env=None,
    argv=None,
    sender=None,
    spawn=None,
) -> bool:
    """Schedule bounded authenticated delivery; return false when suppressed."""
    try:
        state = telemetry_state(site, env=env, argv=argv)
        if not state["enabled"] or not token:
            return False
        body = create_tool_job_completed_event(
            source=source,
            installation_id=config.get_installation_id(),
            tool=tool,
            command_family=command_family,
            tool_version=tool_version,
            output_kind=output_kind,
        )

        def deliver():
            try:
                if sender is not None:
                    sender(site, body, token, TIMEOUT_SECONDS)
                else:
                    api.post_json(
                        str(site).rstrip("/"),
                        event_path,
                        body,
                        token=token,
                        timeout=TIMEOUT_SECONDS,
                    )
            except Exception:
                pass

        if spawn is not None:
            spawn(deliver)
        else:
            threading.Thread(target=deliver, daemon=True).start()
        return True
    except Exception:
        return False
